{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# set_partition"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/set_partition.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/set_partition.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Set partition problem in Google CP Solver.\n",
    "\n",
    "  Problem formulation from\n",
    "  http://www.koalog.com/resources/samples/PartitionProblem.java.html\n",
    "  '''\n",
    "   This is a partition problem.\n",
    "   Given the set S = {1, 2, ..., n},\n",
    "   it consists in finding two sets A and B such that:\n",
    "\n",
    "     A U B = S,\n",
    "     |A| = |B|,\n",
    "     sum(A) = sum(B),\n",
    "     sum_squares(A) = sum_squares(B)\n",
    "\n",
    "  '''\n",
    "\n",
    "  This model uses a binary matrix to represent the sets.\n",
    "\n",
    "\n",
    "  Also, compare with other models which uses var sets:\n",
    "  * MiniZinc: http://www.hakank.org/minizinc/set_partition.mzn\n",
    "  * Gecode/R: http://www.hakank.org/gecode_r/set_partition.rb\n",
    "  * Comet: http://hakank.org/comet/set_partition.co\n",
    "  * Gecode: http://hakank.org/gecode/set_partition.cpp\n",
    "  * ECLiPSe: http://hakank.org/eclipse/set_partition.ecl\n",
    "  * SICStus: http://hakank.org/sicstus/set_partition.pl\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "#\n",
    "# Partition the sets (binary matrix representation).\n",
    "#\n",
    "def partition_sets(x, num_sets, n):\n",
    "  solver = list(x.values())[0].solver()\n",
    "\n",
    "  for i in range(num_sets):\n",
    "    for j in range(num_sets):\n",
    "      if i != j:\n",
    "        b = solver.Sum([x[i, k] * x[j, k] for k in range(n)])\n",
    "        solver.Add(b == 0)\n",
    "\n",
    "  # ensure that all integers is in\n",
    "  # (exactly) one partition\n",
    "  b = [x[i, j] for i in range(num_sets) for j in range(n)]\n",
    "  solver.Add(solver.Sum(b) == n)\n",
    "\n",
    "\n",
    "def main(n=16, num_sets=2):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"Set partition\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  print(\"n:\", n)\n",
    "  print(\"num_sets:\", num_sets)\n",
    "  print()\n",
    "\n",
    "  # Check sizes\n",
    "  assert n % num_sets == 0, \"Equal sets is not possible.\"\n",
    "\n",
    "  #\n",
    "  # variables\n",
    "  #\n",
    "\n",
    "  # the set\n",
    "  a = {}\n",
    "  for i in range(num_sets):\n",
    "    for j in range(n):\n",
    "      a[i, j] = solver.IntVar(0, 1, \"a[%i,%i]\" % (i, j))\n",
    "\n",
    "  a_flat = [a[i, j] for i in range(num_sets) for j in range(n)]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "\n",
    "  # partition set\n",
    "  partition_sets(a, num_sets, n)\n",
    "\n",
    "  for i in range(num_sets):\n",
    "    for j in range(i, num_sets):\n",
    "\n",
    "      # same cardinality\n",
    "      solver.Add(\n",
    "          solver.Sum([a[i, k] for k in range(n)]) == solver.Sum(\n",
    "              [a[j, k] for k in range(n)]))\n",
    "\n",
    "      # same sum\n",
    "      solver.Add(\n",
    "          solver.Sum([k * a[i, k] for k in range(n)]) == solver.Sum(\n",
    "              [k * a[j, k] for k in range(n)]))\n",
    "\n",
    "      # same sum squared\n",
    "      solver.Add(\n",
    "          solver.Sum([(k * a[i, k]) * (k * a[i, k]) for k in range(n)]) ==\n",
    "          solver.Sum([(k * a[j, k]) * (k * a[j, k]) for k in range(n)]))\n",
    "\n",
    "  # symmetry breaking for num_sets == 2\n",
    "  if num_sets == 2:\n",
    "    solver.Add(a[0, 0] == 1)\n",
    "\n",
    "  #\n",
    "  # search and result\n",
    "  #\n",
    "  db = solver.Phase(a_flat, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT)\n",
    "\n",
    "  solver.NewSearch(db)\n",
    "\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    a_val = {}\n",
    "    for i in range(num_sets):\n",
    "      for j in range(n):\n",
    "        a_val[i, j] = a[i, j].Value()\n",
    "\n",
    "    sq = sum([(j + 1) * a_val[0, j] for j in range(n)])\n",
    "    print(\"sums:\", sq)\n",
    "    sq2 = sum([((j + 1) * a_val[0, j])**2 for j in range(n)])\n",
    "    print(\"sums squared:\", sq2)\n",
    "\n",
    "    for i in range(num_sets):\n",
    "      if sum([a_val[i, j] for j in range(n)]):\n",
    "        print(i + 1, \":\", end=\" \")\n",
    "        for j in range(n):\n",
    "          if a_val[i, j] == 1:\n",
    "            print(j + 1, end=\" \")\n",
    "        print()\n",
    "\n",
    "    print()\n",
    "    num_solutions += 1\n",
    "\n",
    "  solver.EndSearch()\n",
    "\n",
    "  print()\n",
    "  print(\"num_solutions:\", num_solutions)\n",
    "  print(\"failures:\", solver.Failures())\n",
    "  print(\"branches:\", solver.Branches())\n",
    "  print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "\n",
    "n = 16\n",
    "num_sets = 2\n",
    "if len(sys.argv) > 1:\n",
    "  n = int(sys.argv[1])\n",
    "if len(sys.argv) > 2:\n",
    "  num_sets = int(sys.argv[2])\n",
    "\n",
    "main(n, num_sets)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
